#include "StdAfx.h"
#include ".\syncobj.h"
#include "Mmsystem.h"
#pragma comment(lib, "Winmm.lib")

CritSect::CritSect()
{
	InitializeCriticalSection(&m_cs);
}

CritSect::~CritSect()
{
	DeleteCriticalSection(&m_cs);	
}

void CritSect::Lock()
{
	EnterCriticalSection(&m_cs);
};

void CritSect::Unlock()
{
	LeaveCriticalSection(&m_cs);	
}

AutoLock::AutoLock(CritSect* cs)
{
	m_cs = cs;
	m_cs->Lock();	
}

AutoLock::~AutoLock()
{
	m_cs->Unlock();
}

MyEvent::MyEvent(BOOL manual)
{
	m_hEvt = CreateEvent(NULL, manual, FALSE, NULL);
}

MyEvent::~MyEvent()
{
	if (m_hEvt)
		CloseHandle(m_hEvt);
}

MyEvent::operator HANDLE () const
{
	return m_hEvt;
}

void MyEvent::Set()
{
	SetEvent(m_hEvt);
}

BOOL MyEvent::Wait(DWORD tmout)
{
	return (WaitForSingleObject(m_hEvt, tmout) == WAIT_OBJECT_0);
}

void MyEvent::Reset()
{
	ResetEvent(m_hEvt);
}

BOOL MyEvent::Check()
{
	return Wait(0);
}

BOOL MsgEvent::WaitMsg(DWORD tmout)
{
	DWORD wait;
	DWORD starttm;

	DWORD waittm = tmout;

	if (waittm != INFINITE)
		starttm = timeGetTime();

	do
	{
		wait = MsgWaitForMultipleObjects(1, &m_hEvt, FALSE, waittm, QS_SENDMESSAGE);
		if (wait = WAIT_OBJECT_0 + 1)
		{
			MSG msg;
			PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE);

			if (waittm != INFINITE)
			{
				DWORD elapsed = timeGetTime()-starttm;

				waittm = (elapsed >= tmout) ? 0 : tmout-elapsed;
			}
		}
	}
	while (wait = WAIT_OBJECT_0 + 1);

	return (wait == WAIT_OBJECT_0);
}
